package spring.security.core.util;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtilsBean;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class CollectionUtils extends org.apache.commons.collections.CollectionUtils{
	
	public static boolean isEmpty(Map<?, ?> map) {
		return map == null || map.isEmpty();
	}

	public static boolean isNotEmpty(Map<?, ?> map) {
		return !isEmpty(map);
	}

	public static <T> Set<T> toPropertySet(Collection<?> collection, String propertyName, Class<T> targetType) {
		if (!isEmpty(collection) && propertyName != null && targetType != null) {
			Set<T> result = new HashSet<>();
			toCollection(collection, propertyName, targetType, result);
			return result;
		} else {
			return Collections.emptySet();
		}
	}

	public static <T> List<T> toPropertyList(Collection<?> collection, String propertyName, Class<T> targetType) {
		if (!isEmpty(collection) && propertyName != null && targetType != null) {
			List<T> result = new ArrayList<>();
			toCollection(collection, propertyName, targetType, result);
			return result;
		} else {
			return Collections.emptyList();
		}
	}

	private static <T> void toCollection(Collection<?> collection, String propertyName, Class<T> targetType,
			Collection<T> result) {
		BeanUtilsBean bub = BeanUtilsBean.getInstance();

		try {
			Iterator<?> e = collection.iterator();

			while (e.hasNext()) {
				Object bean = e.next();
				T value = (T) bub.getPropertyUtils().getSimpleProperty(bean, propertyName);
				if (!targetType.isInstance(value)) {
					throw new ClassCastException();
				}

				result.add(value);
			}

		} catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException arg7) {
			throw new RuntimeException(arg7);
		}
	}

	public static <K, V> Map<K, V> toBeanMap(Collection<V> collection, String propertyName, Class<K> targetType) {
		if (!isEmpty(collection) && propertyName != null && targetType != null) {
			Map result = new HashMap();
			BeanUtilsBean bub = BeanUtilsBean.getInstance();

			try {
				HashSet e = new HashSet();
				Iterator arg5 = collection.iterator();

				while (arg5.hasNext()) {
					Object bean = arg5.next();
					Object value = bub.getPropertyUtils().getSimpleProperty(bean, propertyName);
					if (!targetType.isInstance(value)) {
						throw new ClassCastException();
					}

					if (!e.add(value)) {
						throw new IllegalStateException("存在重复的属性值: " + value);
					}

					result.put(value, bean);
				}

				return result;
			} catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException arg9) {
				throw new RuntimeException(arg9);
			}
		} else {
			return Collections.emptyMap();
		}
	}
}
